#!/usr/bin/python3
# -*- coding:utf-8 -*-

import json
import os
import sys
from urllib.parse import unquote

from flask import Flask, jsonify, request
from flask_cors import *

import config
import mongodb
import urls
from reslutJson import ResultError, ResultSuccess

"""webapp"""

app = Flask(__name__)
CORS(app, supports_credentials=True)

mongo = mongodb.mongo()


@app.route("/")
def index():
    return "data that analysis"


@app.route("/api/db/collection/all", methods=["GET"])
def getcollections(url=None):
    if request.method == "GET":
        li = mongo.allcollections()
        if li:
            return jsonify(ResultSuccess(200, li))
        return jsonify(ResultError(202, "None"))


@app.route("/api/db/collection/<url>", methods=["DELETE"])
def delcollections(url=None):
    if request.method == "DELETE":
        if url is None:
            return jsonify(ResultError(201, "None"))
        if mongo.dropcollections(url):
            return jsonify(ResultSuccess(200, "Success"))
        return jsonify(ResultError(202, "Fail"))


@app.route("/api/db/spider/save", methods=["POST"])
def dboperatons(type=None):
    if request.method == "POST":
        try:
            data_json = json.loads(request.get_data().decode('utf-8'))
            tree = data_json.get("tree")
            bar = data_json.get("bar")
            pie = data_json.get("pie")
            data = {
                'tree': tree,
                'bar': bar,
                'pie': pie
            }
        except Exception as e:
            app.logger.error(e)
            data = None
        if data is None:
            return jsonify("")
        if mongo.spider2DB(data):
            pass
        return ""


@app.route("/api/analysis/<protocol>/<uri>", methods=["POST"])
def analysis(protocol=None, uri=None):
    if uri is None or protocol is None:
        return jsonify(ResultError(210, "参数不正确"))
    # print(protocol + "\t" + url)
    if request.method == "POST":
        try:
            data_json = json.loads(request.get_data().decode('utf-8'))
            depth = data_json.get('depth')
        except Exception as e:
            app.logger.error(e)
            depth = None
        url = protocol + "://" + uri
        print(url)

        if not urls.match(url):
            return jsonify(ResultError(204, "非法url"))

        status_code = urls.testUrl(url)

        if status_code != 200:
            return jsonify(ResultError(208, "url不可访问"))

        website = urls.getdomains(url)

        code = mongo.checkinDB(gtype="pie", domains=website)
        app.logger.info(code)
        if code > 0:
            return jsonify(ResultSuccess(200, "数据库查询到该数据"))
        elif code == -1:
            return jsonify(ResultError(500, "数据库无数据"))
        return do_analysis(url, depth)


@app.route("/api/graph/<gtype>/<domains>", methods=["GET"])
def graph(gtype=None, domains=None):
    app.logger.info("api/graph/" + gtype + "/" + domains)
    if request.method == "GET":
        if gtype and domains:
            try:
                x = mongo.getDict(gtype=gtype, domains=domains)
                dates = []
                for item in x:
                    dates.append(item["date"])
                # print(dates)
                index = dates.index(max(dates))
                # print(index)
                return jsonify(ResultSuccess(200, x[index]))
            except ValueError as e:
                app.logger.error(e)
                return jsonify(ResultError(500, "数据库无数据"))
            except Exception as e:
                app.logger.error(e)
                return jsonify(ResultError(500, "数据库异常"))
        else:
            return jsonify(ResultError(210, "参数不正确"))


def do_analysis(url, depth=None):
    app.logger.info("doAnalysis------------------------------------")
    if not url:
        return jsonify(ResultError(204, "url为空"))
    try:

        # 用户指定爬取深度
        rs = os.system(
            '''curl ''' + config.scrapyd_schedule_url +
            ''' -d project=''' + config.scrapy_project_name +
            ''' -d spider=''' + config.scrapy_spider_name +
            ''' -d s_url="''' + url + '''"''' + ((
                ''' -d depth=''' + str(depth)) if depth else ''''''))  # Python 中的三目表达式代替

        app.logger.debug(rs)
        result = 1
    except Exception as e:
        # print(e)
        app.logger.error(e)
        result = 0
    # print(result)
    if result >= 1:
        return jsonify(ResultError(201, "分析已提交，请等待(long time..)"))
    else:
        return jsonify(ResultError(203, "服务器执行错误"))


if __name__ == "__main__":
    app.debug = True
    app.run(host='0.0.0.0', port=5000)
